package org.example.ballgamedemo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

public class BouncingBallApp extends Application {

    public static String PREFIX = System.getProperty("user.dir");
    public static final String RECORD_PATH = "\\scores.txt";

    static {
        try {
            File file = new File(PREFIX + RECORD_PATH);
            if (!file.exists()) {
                file.createNewFile();
                // 初始化10条空记录
                BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                for (int i = 0; i < 15; i++) {
                    writer.write("匿名玩家 0\n");
                }
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start(Stage stage) {
        BallPane ballPane = new BallPane();
        Scene scene = new Scene(ballPane, 600, 400);

        ballPane.prefWidthProperty().bind(scene.widthProperty());
        ballPane.prefHeightProperty().bind(scene.heightProperty());
        stage.setTitle("曼巴弹球");
        stage.setScene(scene);
        stage.show();
        ballPane.requestFocus(); // 启用键盘监听

        stage.setOnCloseRequest(e -> {
            e.consume(); // 阻止默认关闭
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("退出游戏");
            alert.setHeaderText("确定要退出吗？");
            alert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    System.exit(0);
                }
            });
        });
        TextInputDialog dialog = new TextInputDialog("玩家1");
        dialog.setTitle("欢迎来到曼巴弹球");
        dialog.setHeaderText("请输入您的昵称");
        Optional<String> result = dialog.showAndWait();
        String playerBottomName  = result.orElse("匿名玩家");  // 默认值处理

        TextInputDialog dialog2 = new TextInputDialog("玩家2");
        dialog2.setTitle("玩家2登录");
        dialog2.setHeaderText("上方玩家请输入昵称");
        Optional<String> result2 = dialog2.showAndWait();
        String playerTopName = result2.orElse("匿名玩家2");

        ballPane.setPlayerName(playerBottomName, playerTopName ); // 将昵称传递到游戏面板
        ballPane.showStartButton();
    }

    public static void main(String[] args) {
        launch(args);
    }
}